package com.itheima.easy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.easy.base.PageResponse;
import com.itheima.easy.constant.AccraditationRecordConstant;
import com.itheima.easy.constant.PendingTasksConstant;
import com.itheima.easy.dto.ContractDto;
import com.itheima.easy.entity.*;
import com.itheima.easy.enums.ContractStatusEnum;
import com.itheima.easy.mapper.*;
import com.itheima.easy.service.ApplicationsService;
import com.itheima.easy.service.ContractService;
import com.itheima.easy.service.ElderService;
import com.itheima.easy.service.MemberService;
import com.itheima.easy.utils.CodeUtil;
import com.itheima.easy.utils.UserThreadLocal;
import com.itheima.easy.vo.ContractVo;
import com.itheima.easy.vo.retreat.ElderVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 合同 Service 实现类
 */
@Service
public class ContractServiceImpl implements ContractService {

    @Autowired
    private ContractMapper contractMapper;

    @Resource
    private MemberService memberService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PendingTasksMapper pendingTasksMapper;

    @Autowired
    private CheckInMapper checkInMapper;

    @Resource
    private ApplicationsMapper applicationsMapper;

    @Resource
    private ElderService elderService;

    @Autowired
    private ApplicationsService applicationsService;

    /**
     * 根据id查询合同
     * @param id 合同id
     * @return 合同实体类
     */
    @Override
    public ContractVo getById(Long id) {
        Contract contract = contractMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(contract, ContractVo.class);
    }

    /**
     * 添加合同
     * @param contractDto 合同dto
     * @return 添加结果
     */
    @Override
    public int sign(ContractDto contractDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractDto, contract);

        // 流程状态 操作记录
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(contractDto.getCheckInId());
        //设置流程状态
        checkIn.setFlowStatus(CheckIn.FlowStatus.SIGN.getCode());
        checkIn.setStatus(CheckIn.Status.FINISHED.getCode());
        checkInMapper.updateByPrimaryKeySelective(checkIn);

        applicationsMapper.updateStatus(checkIn.getCheckInCode(), LocalDateTime.now(), CheckIn.Status.FINISHED.getCode());

        //  操作记录
        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        //修改之前的待办任务状态，为已处理
        pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_FINISHED, user.getId());

        //记录操作记录
        applicationsService.insert(null, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_PASS, "同意");
//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion("同意");
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_PASS);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());
//        //保存审核（操作）记录
//        accraditationRecordMapper.insert(accraditationRecord);

        ElderVo elderVo = elderService.selectByPrimaryKey(checkIn.getElderId());
        contract.setElderName(elderVo.getName());
        contract.setContractNo(CodeUtil.generateCode("HT", redisTemplate, 5));
        contract.setElderId(checkIn.getElderId());
        contract.setCheckInNo(checkIn.getCheckInCode());
        contract.setStatus(ContractStatusEnum.PENDING_EFFECTIVE.getOrdinal());
        return contractMapper.insert(contract);
    }

    /**
     * 更新合同
     * @param contractDto 合同dto
     * @return 更新结果
     */
    @Override
    public int update(ContractDto contractDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractDto, contract);
        return contractMapper.updateByPrimaryKey(contract);
    }

    /**
     * 根据id删除合同
     * @param id 合同id
     * @return 删除结果
     */
    @Override
    public int deleteById(Long id) {
        return contractMapper.deleteByPrimaryKey(id);
    }

    /**
     * 分页查询合同信息
     *
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param contractNo 合同编号
     * @param elderName 老人姓名
     * @param status 合同状态
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 分页结果
     */
    @Override
    public PageResponse<ContractVo> selectByPage(Integer pageNum, Integer pageSize, String contractNo, String elderName,
                                                 Integer status, LocalDateTime startTime, LocalDateTime endTime) {
        PageHelper.startPage(pageNum, pageSize);

        // 通过丙方手机号关联合同
        String phone = null;
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            Member byId = memberService.getById(userId);
            if (ObjectUtil.isNotEmpty(byId)) {
                phone = byId.getPhone();
            }
        }
        Page<List<Contract>> page = contractMapper.selectByPage(phone, contractNo, elderName, status, startTime, endTime);
        return PageResponse.of(page, ContractVo.class);
    }

    @Override
    public List<Contract> listAllContracts() {
        return contractMapper.listAllContracts();
    }

    @Override
    public void updateBatchById(List<Contract> updateList) {
        updateList.forEach(v -> {
            contractMapper.updateByPrimaryKeySelective(v);
        });
    }

    @Override
    public List<ContractVo> listByMemberPhone(String phone) {
        return contractMapper.listByMemberPhone(phone);
    }
}


